package com.zidongxiangxi.sharding.job.core.listener;

import com.zidongxiangxi.sharding.job.core.ShardingJob;
import com.zidongxiangxi.sharding.job.core.node.InstancesNode;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type;

/**
 * 实例变更监听
 *
 * @author chenxudong
 * @date 2021/02/19
 */
public class InstancesNodeChangeListener extends AbstractNodeChangeListener {
    private final ShardingJob job;
    private final InstancesNode instancesNode;

    public InstancesNodeChangeListener(ShardingJob job) {
        this.job = job;
        this.instancesNode = job.getInstancesNode();
    }

    @Override
    public boolean canHandleChange(String path, Type eventType) {
        return !job.isPaused() && !job.isShutdown() && instancesNode.isInstanceIdPath(path);
    }

    @Override
    void dealDataChange(String path, Type eventType, String data) {
        if (Type.NODE_REMOVED == eventType) {
            if (instancesNode.isLocalInstancePath(path) && !isReconnectedRegistryCenter()) {
                job.shutdown();
            } else {
                job.shardingFailover(path.substring(path.lastIndexOf("/") + 1));
            }
        } else if (Type.NODE_ADDED == eventType) {
            job.reSharding();
        }
    }

    private boolean isReconnectedRegistryCenter() {
        return instancesNode.isLocalJobInstanceExisted();
    }
}
